<template>
  <div class="page-bg">
    <div class="logo-container">
      <img src="@/assets/img/login/logo.png" alt="Logo" class="logo" />
    </div>
    <div class="text-container">
      <h1 class="title">数字化投资系统</h1>
    </div>

    <div class="login-container">
      <div class="left-image">
        <img src="@/assets/img/login/1.png" alt="Left Image" />
      </div>

      <div class="login-box">
        <div class="login-title-container">
          <h2 class="login-title">欢迎登录</h2>
        </div>
        <el-tabs v-model="activeTab" class="tabs" @tab-click="handleTabClick">
          <el-tab-pane label="个人" name="person" />
          <el-tab-pane label="管理人员" name="admin" />
          <!-- <el-tab-pane label="注册" name="register" /> -->
        </el-tabs>

        <el-form ref="formRef" :model="form" :rules="rules" size="large">
          <el-form-item prop="username">
            <el-input v-model="form.username" placeholder="请输入账户" clearable>
              <template #prefix>
                <img src="@/assets/img/login/icon-account.png" class="icon" />
              </template>
            </el-input>
          </el-form-item>

          <el-form-item prop="password">
            <el-input v-model="form.password" type="password" placeholder="请输入密码" show-password clearable>
              <template #prefix>
                <img src="@/assets/img/login/icon-password.png" class="icon" />
              </template>
            </el-input>
          </el-form-item>

          <el-form-item prop="captcha">
            <div class="captcha-container">
              <el-input v-model="form.captcha" placeholder="请输入验证码" clearable class="captcha-input">
                <template #prefix>
                  <img src="@/assets/img/login/icon-captcha.png" class="icon" />
                </template>
              </el-input>
              <img :src="imgUrl" class="captcha-image" @click="refreshCaptcha" />
              <img src="@/assets/img/login/image.png" class="refresh-icon" @click="refreshCaptcha" />
            </div>
          </el-form-item>

          <el-form-item>
            <div class="login-options">
              <el-checkbox v-model="form.remember">自动登录</el-checkbox>
              <router-link to="/forgot-password" class="forgot-password">忘记密码？</router-link>
            </div>
          </el-form-item>

          <el-button type="primary" class="w-full" :loading="loading" @click="handleSubmit">
            {{ activeTab === 'register' ? '注册' : '登录' }}
          </el-button>
        </el-form>
      </div>
    </div>

    <div class="copyright">
      <h1>版权所有：©山西汾飞信息技术有限公司,山西综改示范区太原唐槐路77号山西智创城1号基地4号楼6层641-642室</h1>
      <h1>备案号:晋ICP备10018730号-1</h1>
    </div>
  </div>
</template>


<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import type { FormRules } from 'element-plus'
import request from '@/utils/http.ts'
import { JSEncrypt } from 'jsencrypt'
import { useRouter } from 'vue-router'

// 添加路由
const router = useRouter()

// RSA公钥
const RSA_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAM51dgYtMyF+tTQt80sfFOpSV27a7t9u
aUVeFrdGiVxscuizE7H8SMntYqfn9lp8a5GH5P1/GGehVjUD2gF/4kcCAwEAAQ==
-----END PUBLIC KEY-----`

// RSA加密函数
function encryptPassword(password: string): string {
  try {
    const encrypt = new JSEncrypt()
    encrypt.setPublicKey(RSA_PUBLIC_KEY)
    const encrypted = encrypt.encrypt(password)
    if (encrypted) {
      return encrypted
    } else {
      console.error('RSA加密失败')
      return password
    }
  } catch (error) {
    console.error('密码加密失败:', error)
    return password
  }
}


const activeTab = ref<'person' | 'admin' | 'register'>('person')
function handleTabClick() {
  formRef.value?.resetFields()
}


const form = reactive({
  username: '',
  password: '',
  captcha: '',
  remember: false
})
const rules: FormRules = {
  username: [{ required: true, message: '请输入账户', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  captcha: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
}

const loading = ref(false)
const formRef = ref()

// 获取验证码
const imgUrl = ref('')
const uuid = ref('')
const refreshCaptcha = async () => {
  try {
    const imageData = await request.get('/captcha/image')
    // console.log(imageData);
    imgUrl.value = imageData.data.img
    uuid.value = imageData.data.uuid
  } catch (error) {
    ElMessage.error('获取验证码失败')
    console.error('获取验证码失败:', error)
  }
}

onMounted(() => {
  refreshCaptcha()
})

async function handleSubmit() {
  try {
    console.log('开始提交表单...');
    await formRef.value!.validate()
    loading.value = true

    // RSA加密密码
    const encryptedPassword = encryptPassword(form.password)
    console.log('原始密码:', form.password);
    console.log('RSA加密后密码:', encryptedPassword);

    const url = 'http://6eab9aa1.r6.cpolar.top/auth/login'

    const requestData = {
      username: form.username,
      password: encryptedPassword,
      captcha: form.captcha,
      uuid: uuid.value
    }

    console.log('请求URL:', url);
    console.log('请求数据:', requestData);
    const { data } = await axios.post(url, requestData)
    console.log('响应数据:', data);

    if (data.data && data.data.token) {

      localStorage.setItem('token', data.data.token)

      ElMessage.success(
        activeTab.value === 'register' ? '注册成功' : '登录成功'
      )

      // 登录成功后跳转到主布局页面
      router.push('/manage')
    } else {
      ElMessage.error(data.msg || '登录失败')
      refreshCaptcha()
    }
  } catch (error: unknown) {
    console.log('请求出错:', error);
    const err = error as { response?: { data?: { msg?: string } } }
    ElMessage.error(err.response?.data?.msg || '网络异常')
    refreshCaptcha()
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.tabs {
  margin-bottom: 20px;
}

:deep(.el-tabs__nav-wrap::after) {
  display: none;
}

:deep(.el-tabs__item) {
  font-size: 16px;
  color: #98A4BF;
  padding: 0 20px 8px 0;
  border: none;
  font-family: 'Microsoft YaHei', Arial, sans-serif;
  font-weight: 400;
}

:deep(.el-tabs__item.is-active) {
  color: #333;
  font-weight: 500;
}

.page-bg {
  min-height: 100vh;
  background-image: url('@/assets/img/login/bg.png') !important;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

.logo-container {
  position: absolute;
  top: 75px;
  left: 81px;
  z-index: 10;
}

.logo {
  width: 51px;
  height: 53px;
  padding: 2px;
}

.text-container {
  position: absolute;
  top: 83px;
  left: 162px;
  z-index: 10;
}

.title {
  font-size: 24px;
  color: #006DB8;
  font-family: 'Microsoft YaHei', Arial, sans-serif;
  font-weight: 500;
  line-height: 32px;
}

.login-container {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 1002px;
  height: auto;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 5px 5px 5px 0 rgba(0, 0, 0, 0, 0.3);
  padding: 79px 0;
}

.left-image {
  width: 374px;
  height: 352px;
  float: left;
  padding: 2px;
  margin-left: 20px;
  margin-left: 20px;
  margin-top: 20px;
}

.login-box {
  width: 400px;
  height: auto;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 5px 5px 5px 0 rgba(0, 0, 0, 0, 0.3);
  padding: 40px;
}

.login-title-container {
  margin-bottom: 20px;
}

.login-title {
  font-size: 24px;
  color: #333;
  font-family: 'Microsoft YaHei', Arial, sans-serif;
  font-weight: 500;
  text-align: left;
  margin: 0;
  padding: 2px;
}

.tabs {
  display: flex;
  justify-content: left;
  margin-bottom: 20px;
  position: relative;
  z-index: 1;
}

.tab-button {
  top: 382px;
  left: 1002px;
  color: #98A4BF;
  font-size: 20px;
  background-color: #fff;
  padding: 0;
  border: 0;
  margin-right: 39px;
  cursor: pointer;
}


.tab-button.active {
  color: #333;
}

.captcha-container {
  display: flex;
  align-items: center;
  gap: 10px;
  width: 100%;
}

.captcha-image {
  width: 96px;
  height: 50px;
}

.refresh-icon {
  width: 25px;
  height: 25px;
  cursor: pointer;
}

.icon {
  width: 35px;
  height: 35px;
  margin: 0 10px;
}

.el-input__inner {
  padding: 5px 10px;
  font-size: 14px;
}

.el-button {
  width: 100%;
  padding: 10px;
  font-size: 16px;
  border-radius: 4px;
}


.text-sm {
  font-size: 14px;

}

.text-blue-600 {
  color: #409EFF;
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.forgot-password {
  color: #006DB8;
  text-decoration: none;
  font-size: 14px;
  font-family: 'Microsoft YaHei', Arial, sans-serif;
}

.forgot-password:hover {
  text-decoration: underline;
}

:deep(.el-checkbox__inner) {
  width: 16px;
  height: 16px;
  border: 2px solid #dcdfe6;
}

:deep(.el-checkbox__inner::after) {
  height: 8px;
  width: 4px;
}

:deep(.el-checkbox__label) {
  font-size: 14px;
  color: #333;
  font-family: 'Microsoft YaHei', Arial, sans-serif;
}


.w-full {
  background-color: #006DB8;
  border-color: #006DB8;
}


.copyright {
  font-size: 12px;
  font-family: 'Microsoft YaHei', Arial, sans-serif;
  font-weight: 400;
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  color: #666;
  text-align: center;
  line-height: 1.5;
}

.tab-button,
.el-button,
.forgot-password,
.refresh-icon {
  transition: all .3s cubic-bezier(.4, 0, .2, 1);
}

.el-button {
  box-shadow: 0 2px 6px rgba(0, 109, 184, .18);
}

.el-button:hover {
  background-color: #0079d4;
  border-color: #0079d4;
  box-shadow: 0 4px 12px rgba(0, 109, 184, .28);
  transform: translateY(-2px) scale(1.02);
}

.el-button:active {
  transform: translateY(0) scale(.98);
  box-shadow: 0 1px 4px rgba(0, 109, 184, .18);
}

.tab-button:hover {
  color: #006DB8;
  transform: translateY(-1px) scale(1.05);
}

.tab-button.active {
  color: #006DB8;
  font-weight: 600;
}

.forgot-password:hover {
  color: #004d8a;
  transform: scale(1.05);
}

.refresh-icon:hover {
  transform: rotate(180deg) scale(1.15);
}

.el-button--primary {
  background-color: #006DB8;
  border-color: #006DB8;
}

.el-button--primary:hover,
.el-button--primary:focus {
  background-color: #006DB8;
  border-color: #006DB8;
  filter: brightness(1.08);
}

.el-button--primary:active {
  background-color: #006DB8;
  border-color: #006DB8;
  filter: brightness(0.95);
}

@media(min-width:1200px) {

  .h1,
  h1 {
    font-size: 16px;
  }
}
</style>
